package com.itheima.interceptor;

import com.itheima.utils.CurrentHolder;
import com.itheima.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * @Author：cxl
 * @Package：com.itheima.interceptor
 * @Project：web-project
 * @name：Inteceptor1
 * @Date：2025-09-30 5:21 pm
 * @Filename：Inteceptor1
 */
@Component
public class Inteceptor implements HandlerInterceptor {
    private static final Logger log = LoggerFactory.getLogger(Inteceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1判断是否是登录请求，是登陆就放行
        String path = request.getRequestURI();
        log.info(path);
        if (StringUtils.endsWithIgnoreCase(path, "/login")) {
            return true;
        }
        //2.如果不是登录就判断token有效性
        String token = request.getHeader("Token");
        if (null != token) {
            log.info("\nInterceptor验证token是否合法");
            try {
                Claims claims = JwtUtils.parseJWT(token);
                Integer userId = claims.get("id", Integer.class);
                log.info("获得到的token{}", claims);
                //存入
                CurrentHolder.setCurrentId(userId);
                return true;
            } catch (Exception e) {
                log.error("token解析失败");
            }
        }
        //设置状态码为401
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        return false;
    }
}
